package com.libcommon

import com.libcommon.mmkv.MKKey
import com.libcommon.mmkv.MKManager
import com.squareup.moshi.FromJson
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

/**
 * CreateBy:Joker
 * CreateTime:2025/5/28/周三 10:47
 * description：
 */
object MoshiManager {

    // 全局 Moshi 实例
    val moshi: Moshi by lazy {
        Moshi.Builder()
            .add(MoShiDateAdapter())            // 注册自定义日期适配器
            .add(KotlinJsonAdapterFactory())    // 添加 Kotlin 反射适配器工厂（必须在最后）
            .build()
    }

    // JSON 转对象
    inline fun <reified T> fromJson(json: String): T? {
        return try {
            val adapter = moshi.adapter(T::class.java)
            adapter.fromJson(json)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 对象转 JSON
    inline fun <reified T> toJson(obj: T): String {
        return try {
            val adapter = moshi.adapter(T::class.java)
            adapter.toJson(obj)
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    inline fun <reified T> fromJsonList(json: String): List<T>? {
        return try {
            val type = Types.newParameterizedType(List::class.java, T::class.java)
            val adapter = moshi.adapter<List<T>>(type)
            adapter.fromJson(json)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    inline fun <reified K, reified V> fromJsonMap(json: String): Map<K, V>? {
        return try {
            val type = Types.newParameterizedType(Map::class.java, K::class.java, V::class.java)
            val adapter = moshi.adapter<Map<K, V>>(type)
            adapter.fromJson(json)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

//    inline fun <reified T> fromJsonResponse(json: String): T? {
//        return try {
//            val type = Types.newParameterizedType(MoShiResponse::class.java, T::class.java)
//            val adapter = moshi.adapter<MoShiResponse<T>>(type)
//            adapter.fromJson(json)?.data
//        } catch (e: Exception) {
//            e.printStackTrace()
//            null
//        }
//    }
//
//    // 假设 API 响应格式
//    @JsonClass(generateAdapter = true)
//    @Keep
//    data class MoShiResponse<T>(
//        val code: Int,
//        val message: String,
//        val data: T?
//    )
}

// JSON 转对象
//val user: User? = MoshiManager.fromJson(jsonString)

// 对象转 JSON
//val json = MoshiManager.toJson(user)

// 解析列表
//val users: List<User>? = MoshiManager.fromJsonList(jsonArrayString)

// 解析响应
//val user: User? = MoshiManager.fromJsonResponse(jsonResponseString)

class MoShiDateAdapter {
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH).apply {
        timeZone = TimeZone.getTimeZone("UTC")
    }

    @ToJson
    fun toJson(date: Date?): String? {
        return date?.let { dateFormat.format(it) }
    }

    @FromJson
    fun fromJson(json: String?): Date? {
        return json?.let { dateFormat.parse(it) }
    }
}

fun formatDataFromJson(response: String): String {
    if (!MKManager.getBoolean(MKKey.JSON_FORMAT)) return response
    try {
        when {
            response.startsWith("{") -> {
                val jsonObject = JSONObject(response)
                return jsonObject.toString(4)
            }

            response.startsWith("[") -> {
                val jsonArray = JSONArray(response)
                return jsonArray.toString(4)
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return response
}